import { constantRoutes, errorRedirectionRoutes, routeMap, createBaseRouter } from '@/router'

function registerAsyncRoutes(asyncRoutes) {
  const routes = []
  asyncRoutes.forEach(item => {
    if (item.children) {
      routes.push({
        ...item, component: routeMap[item.componentName], children: registerAsyncRoutes(item.children)
      })
    } else {
      routes.push({ ...item, component: routeMap[item.componentName] })
    }
  })
  return routes
}

const state = {
  routes: [], // 可访问的路由列表
  addRoutes: [] // 动态注册生成的路由
}
const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = createBaseRouter(constantRoutes.concat(routes)).getRoutes().map(item => item.path)
  }
}
const actions = {
  generateRoutes({ commit, state }, routes = []) {
    return new Promise(resolve => {
      const accessedRoutes = [...registerAsyncRoutes(routes), ...errorRedirectionRoutes]
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
  authorityVerification({ state }, to) {
    const { path } = to
    if (path) {
      return state.routes.includes(path)
    } else {
      return false
    }
  }
}

export default {
  namespace: true,
  state,
  mutations,
  actions
}
